import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class TcpSend {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 5000);
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        Scanner scanner = new Scanner(System.in);

        // 告诉服务器是要加密还是解密
        while (true) {
            System.out.println("请输入文件需要加密还是解密：1.加密 2.解密");
            int choose = scanner.nextInt();
            if (choose != 1 && choose != 2) {
                System.out.println("输入错误，请重新输入");
            } else {
                outputStream.write(ByteToInt.toBytes(choose));
                break;
            }
        }

        // 写文件，先写文件的名字和长度
        // /Users/edz/banyuan/Java/20.Socket/practice/02.tcp/alice.code
        System.out.println("请输入需要加密或者解密的文件路径：");
        String InputAddress = scanner.next();
        File file = new File(InputAddress);
        FileInfo fileInfo = new FileInfo(file.getName(), file.length());
        // 将文件信息转为json对象的字符串形式
        String fileInfoStr = JSONObject.toJSONString(fileInfo);
        outputStream.write(ByteToInt.toBytes(fileInfoStr.getBytes().length));
        outputStream.write(fileInfoStr.getBytes());

        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[1024];
        int count = bufferedInputStream.read(buf);
        while (count > 0) {
            outputStream.write(buf, 0, count);
            count = bufferedInputStream.read(buf);
        }



        File newFile = new File("/Users/edz/banyuan/Java/20.Socket/practice/02.tcp", "Refine" + file.getName());
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(newFile));

        long fileLeft = file.length();
        int read = inputStream.read(buf, 0, (int) Math.min(fileLeft, buf.length));
        while (fileLeft>0){
            bufferedOutputStream.write(buf,0,read);
            fileLeft-=read;
            read = inputStream.read(buf,0,(int) Math.min(fileLeft, buf.length));
        }
        bufferedInputStream.close();
        bufferedOutputStream.close();
        socket.close();
    }

    private static byte[] getBytes(InputStream inputStream, int total) throws IOException {
        byte[] lengthBytes = new byte[total];
        int len = inputStream.read(lengthBytes);
        if (len != lengthBytes.length) {
            throw new IllegalArgumentException("读取长度错误");
        }
        return lengthBytes;
    }
}
